package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.bean.ShoppingCart;
import com.itheima.commons.BaseContext;
import com.itheima.commons.R;
import com.itheima.exception.CustomException;
import com.itheima.service.ShoppingCartService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @author Tang
 * @date 2023/1/12
 */
@Slf4j
@RequestMapping("/shoppingCart")
@RestController
public class ShoppingCartController {
    @Autowired
    private ShoppingCartService shoppingCartService;

    /**
     * 添加购物车
     * @param shoppingCart
     * @return
     */
    @PostMapping("/add")
    public R<ShoppingCart> addShoppingCart(@RequestBody ShoppingCart shoppingCart){
        //0. 获取当前登录用户的id
        Long userId = BaseContext.getCurrentId();

        if (shoppingCart == null) {
            throw new CustomException("请先选择商品添加到购物车！");
        }

        //1. 判断当前购物车中是否存在该商品  唯一的判断  eg：添加第一条数据---辣椒炒肉：口味信息 微辣  又添加一条辣椒炒肉，口味信息：重辣
        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getUserId, userId);
        if (shoppingCart.getDishId() != null) {  //如果是添加菜品
            queryWrapper.eq(ShoppingCart::getDishId, shoppingCart.getDishId());
            queryWrapper.eq(shoppingCart.getDishFlavor()!=null, ShoppingCart::getDishFlavor, shoppingCart.getDishFlavor());
        } else {                                //添加套餐
            queryWrapper.eq(ShoppingCart::getSetmealId, shoppingCart.getSetmealId());
        }
        ShoppingCart cart = shoppingCartService.getOne(queryWrapper);

        //2. 如果存在该商品，直接number数量+1
        if (cart != null) {
            cart.setNumber(cart.getNumber() + 1);
        } else {
            //3. 如果不存在该商品，需要补齐一些字段：user_id、number、crate_time
            cart = shoppingCart;
            cart.setNumber(1);  //添加商品默认数量为1
            cart.setUserId(userId); //关联用户id
            cart.setCreateTime(LocalDateTime.now());
        }

        //4. 调用service保存购物车数据  这里使用saveOrUpdate  新增或更新
        shoppingCartService.saveOrUpdate(cart);

        //5. 返回结果
        return R.success(cart);
    }

    /**
     * 查询购物车
     * @return
     */
    @GetMapping("/list")
    public R<List<ShoppingCart>> list() {
        //【特别注意】需要查询的是当前用户的购物车数据
        //1.获取当前登录用户的id
        Long userId = BaseContext.getCurrentId();
        if (userId == null) {
            throw new CustomException("该用户不存在！");
        }
        //2.根据当前用户id查询购物车
        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getUserId, userId);
        List<ShoppingCart> list = shoppingCartService.list(queryWrapper);

        //3.返回结果
        return R.success(list);
    }

    /**
     * 清空购物车
     * @return
     */
    @DeleteMapping("/clean")
    public R<String> clean() {
        //1.获取当前登录用户的id
        Long userId = BaseContext.getCurrentId();
        if (userId == null) {
            throw new CustomException("该用户不存在！");
        }

        //2.根据当前用户id清空购物车，调用service删除方法
        LambdaQueryWrapper<ShoppingCart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ShoppingCart::getUserId, userId);
        boolean flag = shoppingCartService.remove(wrapper);

        //3.返回结果
        return flag ? R.success("清空购物车成功！"):R.error("清空购物车失败！");
    }

    /**
     * 指定商品数量减一
     * @param shoppingCart
     * @return
     */
    @PostMapping("/sub")
    public R<ShoppingCart> sub(@RequestBody ShoppingCart shoppingCart){

        LambdaQueryWrapper<ShoppingCart> lqw = new LambdaQueryWrapper<>();
        lqw.eq(ShoppingCart::getUserId,BaseContext.getCurrentId());
        lqw.eq(ShoppingCart::getDishId,shoppingCart.getDishId());

        ShoppingCart one = shoppingCartService.getOne(lqw);
        if (one == null){
            throw new CustomException("菜品不存在");
        }

        if(one.getNumber() > 1){
            //菜品数量大于1,减一存入
            one.setNumber(one.getNumber() - 1);
            shoppingCartService.updateById(one);
        }else {
            one.setNumber(one.getNumber() - 1);
            shoppingCartService.removeById(one);

        }

        return R.success(one);
    }
}
